import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  Tree,
  TreeParent,
  TreeChildren,
  ManyToMany,
  getManager,
} from 'typeorm';
import { Role } from '../../role/entities/role.entity';

@Entity()
@Tree('closure-table')
export class Permission {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ unique: true })
  permCode?: string; // 权限名称，例如 "create_post"

  @Column({ type: 'varchar', length: 20, comment: '权限描述' })
  permName: string; // 权限描述

  // 权限可以被多个角色拥有
  @ManyToMany(() => Role, (role) => role.permissions)
  roles: Role[];

  @TreeParent()
  parent: Permission;

  @TreeChildren()
  children: Permission[];

  @Column({
    type: 'integer',
    comment: '排序',
    default: 0,
  })
  sort?: number;

  @Column({
    type: 'datetime',
    default: () => 'CURRENT_TIMESTAMP',
    comment: '创建时间',
  })
  create_time: Date;

  @Column({
    type: 'datetime',
    default: () => 'CURRENT_TIMESTAMP',
    onUpdate: 'CURRENT_TIMESTAMP',
    comment: '更新时间',
  })
  update_time: Date;

  @Column({ type: 'boolean', comment: '是否禁用', default: false })
  is_disabled: boolean;

  @Column({ type: 'boolean', comment: '是否删除', default: false })
  is_deleted: boolean;

  @Column({ type: 'datetime', comment: '禁用时间', default: null })
  disabled_time: Date;

  @Column({ type: 'datetime', comment: '删除时间', default: null })
  delete_time: Date;

  async isChildOf(parentId: string): Promise<boolean> {
    const manager = getManager();
    const repository = manager.getRepository(Permission);
    const parentPermission = await repository.findOne({
      where: { id: parentId },
      relations: ['children'],
    });
    if (!parentPermission) {
      return false;
    }
    const childIds = parentPermission.children.map((child) => child.id);
    return childIds.includes(this.id);
  }
}
